package com.shop.cereshop.app.dl.logic.service.Impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shop.cereshop.app.dao.dl.CareShopNewsForwardLogMapper;
import com.shop.cereshop.app.dao.dl.CereBuyerUserMapper;
import com.shop.cereshop.app.dao.dl.CerePlatformUserPointMapper;
import com.shop.cereshop.app.dao.order.CereShopOrderDAO;
import com.shop.cereshop.app.dl.logic.domain.CareShopNewsForwardLog;
import com.shop.cereshop.app.dl.logic.domain.CereBuyerUser;
import com.shop.cereshop.app.dl.logic.domain.CerePlatformUserPoint;
import com.shop.cereshop.app.dl.logic.domain.CereShopProduct;
import com.shop.cereshop.app.dl.logic.service.CerePlatformUserPointService;
import com.shop.cereshop.app.dl.logic.utils.ResultInfo;
import com.shop.cereshop.app.dl.logic.vo.PointsDetails;
import com.shop.cereshop.app.dl.logic.vo.RedemptionRecord;
import com.shop.cereshop.app.domain.TicketInfo.CereShopTicketInfo;
import com.shop.cereshop.app.page.cart.CartSku;
import com.shop.cereshop.app.page.order.OrderProductAttribute;
import com.shop.cereshop.app.page.order.PayUrl;
import com.shop.cereshop.app.param.order.OrderParam;
import com.shop.cereshop.app.param.order.OrderProductParam;
import com.shop.cereshop.app.param.settlement.ProductSku;
import com.shop.cereshop.app.redis.service.api.StringRedisService;
import com.shop.cereshop.app.service.activity.CereBuyerCouponService;
import com.shop.cereshop.app.service.buyer.CereBuyerReceiveService;
import com.shop.cereshop.app.service.buyer.CereBuyerShopCouponService;
import com.shop.cereshop.app.service.cart.CereShopCartService;
import com.shop.cereshop.app.service.order.CereOrderParentService;
import com.shop.cereshop.app.service.order.CereOrderProductAttributeService;
import com.shop.cereshop.app.service.order.CereOrderProductService;
import com.shop.cereshop.app.service.product.CereProductSkuService;
import com.shop.cereshop.app.service.redis.CereRedisKeyServcice;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.constant.StringEnum;
import com.shop.cereshop.commons.domain.activity.CereBuyerCoupon;
import com.shop.cereshop.commons.domain.buyer.CereBuyerReceive;
import com.shop.cereshop.commons.domain.buyer.CereBuyerShopCoupon;
import com.shop.cereshop.commons.domain.order.CereOrderParent;
import com.shop.cereshop.commons.domain.order.CereOrderProduct;
import com.shop.cereshop.commons.domain.order.CereShopOrder;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.RandomStringUtil;
import com.shop.cereshop.commons.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

/**
 * @program: dlshop
 * 描述：
 * @author: 我好帅
 * @create: 2021-06-15 17:15
 **/
@Service
@Transactional
public class CerePlatformUserPointServiceImpl implements CerePlatformUserPointService {

    @Value("${weixin.appid}")
    private String appid;
    @Value("${integral}")
    private Integer integral;
    @Autowired
    private CerePlatformUserPointMapper cerePlatformUserPointMapper;
    @Autowired
    private CareShopNewsForwardLogMapper careShopNewsForwardLogMapper;
    @Autowired
    private CereBuyerUserMapper cereBuyerUserMapper;


    @Override
    public ResultInfo<?> transpondGetIntegral(Long buyerUserId, Integer newsId,String time) {
        if (buyerUserId==0){
            return new ResultInfo<>();
        }
        CereBuyerUser cereBuyerUser = cereBuyerUserMapper.selectByPrimaryKey(buyerUserId);
        Date date = TimeUtils.yyMMddHHmmss2(time);
        //查询今日积分记录
        String s = TimeUtils.yyMMddHHmmss3(date);
        CareShopNewsForwardLog careShopNewsForwardLog = careShopNewsForwardLogMapper.selectTime(buyerUserId, newsId,s);
        //等于null(数据库没有今天转发记录表), 表示今日未转发获得积分
        if (careShopNewsForwardLog == null) {
            CerePlatformUserPoint cerePlatformUserPoint = new CerePlatformUserPoint();
            cerePlatformUserPoint.setBuyerUserId(buyerUserId);
            cerePlatformUserPoint.setNewsId(Long.valueOf(newsId));
            cerePlatformUserPoint.setPoints(integral);
            //来源类型(暂时默认0)
            cerePlatformUserPoint.setSourceType((short) 0);
            //积分来源说明
            cerePlatformUserPoint.setMemo("转发获得");
            //转发积分时间

            cerePlatformUserPoint.setTime(date);
            //积分表新增一条数据
            int i = cerePlatformUserPointMapper.insert(cerePlatformUserPoint);

            CareShopNewsForwardLog careShopNewsForwardLog1 = new CareShopNewsForwardLog();
            careShopNewsForwardLog1.setNewsId(Long.valueOf(newsId));
            careShopNewsForwardLog1.setBuyerUserId(buyerUserId);
            careShopNewsForwardLog1.setForwardTime(date);
            careShopNewsForwardLog1.setBuyerUserName(cereBuyerUser.getName());
            //转发记录表新增一条数据
            int j = careShopNewsForwardLogMapper.insert(careShopNewsForwardLog1);
            if (i > 0 && j > 0) {
                return new ResultInfo<>(200, "转发成功");
            }
        }
        return new ResultInfo<>();
    }

    @Override
    public ResultInfo<?> getAllByUserid(Integer page, Integer row, Long buyerUserId) {
        PageHelper.startPage(page, row);
        List<PointsDetails> list = new ArrayList<>();
        List<CerePlatformUserPoint> list2 = cerePlatformUserPointMapper.getAllByUserid(buyerUserId);
        for (CerePlatformUserPoint c : list2) {
            PointsDetails p = new PointsDetails();
            p.setIntegral(c.getPoints());
            p.setMemo(c.getMemo());
            p.setTime(c.getTime());
            list.add(p);
        }
        PageInfo<?> pageInfo = new PageInfo<>(list);
        return new ResultInfo<>(pageInfo);
    }

    //积分兑换记录
    @Override
    public ResultInfo<?> pointsRedemptionRecord(Integer page, Integer row, Long buyerUserId) {
        PageHelper.startPage(page, row);
        List<CerePlatformUserPoint> list = cerePlatformUserPointMapper.pointsRedemptionRecord(buyerUserId);
        List<RedemptionRecord> list1 = new ArrayList<>();
        for (CerePlatformUserPoint c : list) {
            RedemptionRecord r = new RedemptionRecord();
            CereShopProduct shopProduct = c.getShopProduct();
            //赋值商品名
            r.setProductName(shopProduct.getProductName());
            //商品图片--商品表关联商品图片表(1个商品对多个规格的图片,暂定1, 这里默认取第一个)
            if (c.getProductImages().size() > 0) {
                r.setMapPath(c.getProductImages().get(0).getProductImage());
            }
            //商品所需积分
            r.setProductPoints((-1) * c.getPoints());
            r.setProductId(c.getProductId());
            //赋值状态
            r.setStatus("成功");
            //兑换时间
            r.setRedemptionTime(c.getTime());
            list1.add(r);
        }
        PageInfo<RedemptionRecord> pageInfo = new PageInfo<>(list1);
        return new ResultInfo<>(pageInfo);
    }

    @Override
    public ResultInfo<?> pointsToRedeemGoods(@RequestBody OrderParam param, com.shop.cereshop.commons.domain.buyer.CereBuyerUser user, String ip) {
        //根据用户id查询总积分
        Integer allPoints = cerePlatformUserPointMapper.selectAllPointsByUserid(user.getBuyerUserId());
        if(allPoints == null){
            allPoints = 0;
        }
        if (param.getPrice().compareTo(new BigDecimal(allPoints)) > 0) {
            return ResultInfo.error(400, "积分不足,兑换失败");
        } else {
            CerePlatformUserPoint point = new CerePlatformUserPoint();
            point.setBuyerUserId(user.getBuyerUserId());
            point.setPoints((-1) * param.getPrice().intValue());
            //积分来源, 默认0
            point.setSourceType((short) 0);
            point.setMemo("积分兑换");
            point.setTime(new Date());
            point.setProductId(param.getProductId());
            int insert = cerePlatformUserPointMapper.insert(point);
            if(insert > 0){
                cereShopOrderDAO.updateByOrderForMid2(param.getOrderFormid());
                return new ResultInfo<>();
            }else {
                return ResultInfo.error("兑换失败");
            }
//            PointShopUtils shop = new PointShopUtils();
//            PayUrl payUrl = new PayUrl();
//            try {
////                payUrl = submit(param, user, ip);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//            if (payUrl != null) {
//                return new ResultInfo<>(payUrl);
//            }
//            return ResultInfo.error("兑换失败");
        }
    }

    //=========================
    @Autowired
    private StringRedisService stringRedisService;
    @Autowired
    private CereOrderProductService cereOrderProductService;

    @Autowired
    private CereShopOrderDAO cereShopOrderDAO;

    @Autowired
    private CereProductSkuService cereProductSkuService;

    @Autowired
    private CereOrderParentService cereOrderParentService;

    @Autowired
    private CereOrderProductAttributeService cereOrderProductAttributeService;

    @Autowired
    private CereRedisKeyServcice cereRedisKeyServcice;

    @Autowired
    private CereBuyerCouponService cereBuyerCouponService;

    @Autowired
    private CereShopCartService cereShopCartService;

    @Autowired
    private CereBuyerReceiveService cereBuyerReceiveService;

    @Autowired
    private CereBuyerShopCouponService cereBuyerShopCouponService;

    public PayUrl submit(OrderParam param, com.shop.cereshop.commons.domain.buyer.CereBuyerUser user, String ip) throws CoBusinessException, Exception {
        PayUrl payUrl = new PayUrl();
        String time = TimeUtils.yyMMddHHmmss();
        if (EmptyUtils.isEmpty(param.getType())) {
            ////////////////////////////////（新增方法）
            CereShopTicketInfo ticketInfo = new CereShopTicketInfo();
            if (!EmptyUtils.isEmpty(param.getBookName())) {
                ticketInfo.setCustomer(param.getBookName());
            }
            if (!EmptyUtils.isEmpty(param.getBookMobile())) {
                ticketInfo.setCustomerTel(param.getBookMobile());
            }
            if (!EmptyUtils.isEmpty(param.getIdCard())) {
                ticketInfo.setCustomerCard(param.getIdCard());
            }
            if (!EmptyUtils.isEmpty(param.getMemo())) {
                ticketInfo.setMemo(param.getMemo());
            }
            if (!EmptyUtils.isEmpty(param.getTravelDate())) {
                ticketInfo.setTravelDate(param.getTravelDate());
            }
            //正常下单
            normalOrder(param, user, ip, payUrl, time, ticketInfo);
        }
        return payUrl;
    }

    private void normalOrder(OrderParam param, com.shop.cereshop.commons.domain.buyer.CereBuyerUser user, String ip, PayUrl payUrl, String time, CereShopTicketInfo ticketInfo) throws CoBusinessException, Exception {
        Map<Long, CartSku> map = new HashMap<>();
        if (!EmptyUtils.isEmpty(param.getShops())) {
            //定义map封装商品购买数量
            Map<Long, ProductSku> numberMap = new HashMap<>();
            param.getShops().forEach(shop -> {
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    shop.getSkus().forEach(sku -> numberMap.put(sku.getSkuId(), sku));
                }
            });
            //校验商品库存
            AtomicBoolean flag = new AtomicBoolean(false);
            //定义运费
            BigDecimal logisticPrice = new BigDecimal(0);
            for (OrderProductParam shop : param.getShops()) {
                if (!EmptyUtils.isEmpty(shop.getDistribution())) {
                    //计算总得运费
                    logisticPrice = logisticPrice.add(shop.getDistribution().getDistributionPrice());
                }
                if (!EmptyUtils.isEmpty(shop.getSkus())) {
                    //查询当前店铺所有购买商品的库存数据
                    List<CartSku> productSkus = cereProductSkuService.findStockNumberBySkus(shop.getSkus());
                    if (!EmptyUtils.isEmpty(productSkus)) {
                        productSkus.forEach(sku -> {
                            //设置购买数量
                            sku.setNumber(numberMap.get(sku.getSkuId()).getNumber());
                            //设置选中状态
                            sku.setSelected(0);
                            //设置店铺id
                            sku.setShopId(shop.getShopId());
                            map.put(sku.getSkuId(), sku);
                        });
                    }
                    shop.getSkus().forEach(sku -> {
                        if (IntegerEnum.NO.getCode().equals(map.get(sku.getSkuId()).getIfOversold())) {
                            //如果不允许超卖,校验redis中商品库存
                            int stockNumber;
                            if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                                stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                            } else {
                                stockNumber = map.get(sku.getSkuId()).getStockNumber();
                            }
                            if (sku.getNumber() > stockNumber) {
                                //如果购买数量大于库存，则设置为true
                                flag.set(true);
                            }
                        }
                    });
                }
            }
            //为true则不再售卖
            if (flag.get()) {
                throw new CoBusinessException(CoReturnFormat.PRODUCT_STOCK_ERROR);
            }
            //计算订单总金额
            BigDecimal orderPrice = setOrderPrice(map, numberMap);
            //查询平台优惠券数据
            CereBuyerCoupon buyerCoupon = cereBuyerCouponService.findByCouponId(param.getCouponId(), user.getBuyerUserId());
            //定义店铺优惠金额map
            Map<Long, CereBuyerShopCoupon> discountMap = new HashMap<>();
            //计算优惠金额
            param.setDiscountPrice(setDiscountPrice(buyerCoupon, param, map, numberMap, discountMap));
            //计算订单实付金额=订单总金额-优惠+运费
            if (!EmptyUtils.isEmpty(logisticPrice)) {
                param.setPrice(orderPrice.subtract(param.getDiscountPrice()).add(logisticPrice));
            } else {
                param.setPrice(orderPrice.subtract(param.getDiscountPrice()));
            }
            //新增父订单数据
            CereOrderParent parent = new CereOrderParent();
            parent.setCreateTime(time);
            parent.setLogisticsPrice(logisticPrice);
            //订单总价
            parent.setOrderPrice(orderPrice);
            parent.setPrice(param.getPrice());
            parent.setParentFormid(RandomStringUtil.getRandomCode(15, 0));
            cereOrderParentService.insert(parent);
            payUrl.setMoney(param.getPrice());
            payUrl.setOrderId(parent.getParentId());
            if (EmptyUtils.isEmptyBigdecimal(payUrl.getMoney())) {
                //如果金额为0,提示
                throw new CoBusinessException(CoReturnFormat.PAY_MONEY_NOT_ZERO);
            }
            //遍历店铺数据,新增订单
            addOrder(parent.getParentId(), param, user, time, map, buyerCoupon, discountMap, ticketInfo);
        }
    }

    private void addOrder(Long parentId, OrderParam param, com.shop.cereshop.commons.domain.buyer.CereBuyerUser user, String time,
                          Map<Long, CartSku> map, CereBuyerCoupon buyerCoupon, Map<Long, CereBuyerShopCoupon> discountMap, CereShopTicketInfo ticketInfo) throws Exception {
        //遍历店铺
        List<CartSku> carts = new ArrayList<>();
        List<CartSku> skus = null;
        if (!EmptyUtils.isEmpty(map)) {
            //拿到所有商品数据
            skus = map.keySet().stream().map(map::get).collect(Collectors.toList());
        }
        //查询所有规格属性数据
        List<OrderProductAttribute> attributes = cereOrderProductAttributeService.findBySkus(skus);
        //查询收货地址数据
        CereBuyerReceive receive = cereBuyerReceiveService.findById(param.getReceiveId());
        if (receive != null) {
            for (OrderProductParam shop : param.getShops()) {
                //封装子订单数据
                CereShopOrder order = new CereShopOrder();
                order.setShopId(shop.getShopId());
                order.setParentId(parentId);
                order.setBuyerUserId(user.getBuyerUserId());
                order.setCreateTime(time);
                order.setUpdateTime(time);
                order.setCouponId(param.getCouponId());
                order.setReceiveName(receive.getReceiveName());
                order.setReceivePhone(receive.getReceivePhone());
                order.setReceiveAdress(receive.getReceiveAdress());
                order.setAddress(receive.getAddress());
                order.setCustomerName(user.getWechatName());
                order.setCustomerPhone(user.getPhone());
                order.setLogisticsPrice(shop.getDistribution().getDistributionPrice());
                order.setLogisticsId(shop.getDistribution().getLogisticsId());
                order.setState(2);
                order.setOrderFormid(RandomStringUtil.getRandomCode(15, 0));
                //定义订单优惠券金额（平台优惠金额/店铺总数+店铺优惠金额）
                BigDecimal discountPrice = new BigDecimal(0);
                if (buyerCoupon != null) {
                    discountPrice = buyerCoupon.getReduceMoney().divide(
                            new BigDecimal(param.getShops().size()), 2, BigDecimal.ROUND_HALF_UP);
                    //更新平台优惠券状态为已使用
                    buyerCoupon.setUpdateTime(time);
                    buyerCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                    cereBuyerCouponService.updateState(buyerCoupon);
                    //删除redis延时任务
                    stringRedisService.delete(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                    //删除redis记录数据
                    cereRedisKeyServcice.deleteByKey(StringEnum.COUPON_OVERDUE.getCode() + "-" + buyerCoupon.getBuyerUserId()
                            + "-" + buyerCoupon.getActivityId() + "-" + buyerCoupon.getFullMoney());
                }
                //计算订单优惠金额
                if (!EmptyUtils.isEmpty(shop.getId()) && !EmptyUtils.isEmpty(discountMap)) {
                    order.setId(shop.getId());
                    if (!EmptyUtils.isEmpty(discountMap.get(shop.getId()))) {
                        CereBuyerShopCoupon cereBuyerShopCoupon = discountMap.get(shop.getId());
                        //更新店铺优惠券状态为已使用
                        cereBuyerShopCoupon.setUpdateTime(time);
                        cereBuyerShopCoupon.setState(IntegerEnum.COUPON_USE.getCode());
                        cereBuyerShopCouponService.updateState(cereBuyerShopCoupon);
                        //删除redis延时任务
                        stringRedisService.delete(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        cereRedisKeyServcice.deleteByKey(StringEnum.SHOP_COUPON_OVERDUE.getCode() + "-" + cereBuyerShopCoupon.getId());
                        order.setShopOperateId(cereBuyerShopCoupon.getShopOperateId());
                        if (!EmptyUtils.isEmptyBigdecimal(discountPrice)) {
                            discountPrice = discountPrice.add(cereBuyerShopCoupon.getReduceMoney());
                        } else {
                            discountPrice = cereBuyerShopCoupon.getReduceMoney();
                        }
                    }
                }
                order.setDiscountPrice(discountPrice);
                if (!EmptyUtils.isEmpty(skus)) {
                    //定义店铺商品总金额字段
                    final BigDecimal[] total = {new BigDecimal(0)};
                    //设置规格数量
                    skus.forEach(sku -> {
                        if (sku.getShopId().equals(shop.getShopId())) {
                            total[0] = total[0].add(sku.getPrice().multiply(
                                    new BigDecimal(sku.getNumber())).setScale(2, BigDecimal.ROUND_HALF_UP));
                        }
                    });
                    //订单总金额=店铺商品总金额+运费
                    order.setOrderPrice(total[0].add(order.getLogisticsPrice()));
                    //订单支付金额=订单总金额-优惠
                    order.setPrice(order.getOrderPrice().subtract(order.getDiscountPrice()));
                    order.setPaymentState(1);
                    order.setPaymentMode(1);
                    order.setRemark(param.getRemark());
                    order.setBuyerUserId(user.getBuyerUserId());
                    //插入订单数据
                    cereShopOrderDAO.insert(order);
                    //插入新增订单附属数据(新增订单附属数据)/////////////////////
                    if (!EmptyUtils.isEmpty(ticketInfo) && !EmptyUtils.isEmpty(order.getOrderId())) {
                        ticketInfo.setOrderId(order.getOrderId());
                        cereShopOrderDAO.insertTicketInfo(ticketInfo);
                    }
                    //新增订单商品数据
                    addOrderProduct(skus, order.getOrderId(), shop.getShopId(), map, carts, attributes);
                    //设置30分钟延时自动取消订单,并且释放库存
                    stringRedisService.set(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), param.getShops(), 30 * 60 * 1000);
                    //新增延时任务记录
                    cereRedisKeyServcice.add(StringEnum.ORDER_AUTOMATIC_CANCEL.getCode() + "-" + order.getOrderId(), TimeUtils.getMinuteAfter(30));
                }
            }
            //批量更新库存数量
            cereProductSkuService.updateBatch(skus);
            //插入规格属性数据
            if (!EmptyUtils.isEmpty(attributes)) {
                cereOrderProductAttributeService.insertBatch(attributes);
            }
        }
        if (!EmptyUtils.isEmpty(carts)) {
            //删除购物车商品
            cereShopCartService.deleteSkus(carts, user.getBuyerUserId());
        }
    }

    private BigDecimal setOrderPrice(Map<Long, CartSku> map, Map<Long, ProductSku> numberMap) {
        BigDecimal total = new BigDecimal(0);
        for (Long skuId : map.keySet()) {
            total = total.add(map.get(skuId).getPrice().multiply(new BigDecimal(numberMap.get(skuId).getNumber())));
        }
        return total;
    }

    private BigDecimal setDiscountPrice(CereBuyerCoupon buyerCoupon, OrderParam param, Map<Long,
            CartSku> map, Map<Long, ProductSku> numberMap, Map<Long, CereBuyerShopCoupon> discountMap) {
        //定义满足优惠券商品价格总计
        BigDecimal total;
        BigDecimal decimal = new BigDecimal(0);
        if (buyerCoupon != null) {
            //加上平台优惠券
            decimal = decimal.add(buyerCoupon.getReduceMoney());
        }
        //查询所有店铺优惠券数据
        List<CereBuyerShopCoupon> list = cereBuyerShopCouponService.findByIds(param.getShops());
        //计算店铺优惠券金额总和
        if (!EmptyUtils.isEmpty(list)) {
            for (CereBuyerShopCoupon cereBuyerShopCoupon : list) {
                total = new BigDecimal(0);
                if (IntegerEnum.COUPON_TYPE_DISCOUNT.getCode().equals(cereBuyerShopCoupon.getCouponType())) {
                    //如果是折扣券,查询改折扣券关联商品id
                    List<Long> ids = cereBuyerShopCouponService.findProductIds(cereBuyerShopCoupon.getShopCouponId());
                    if (!EmptyUtils.isEmpty(param.getShops())) {
                        //遍历购买商品
                        if (!EmptyUtils.isEmpty(map)) {
                            for (Long key : map.keySet()) {
                                if (ids.contains(map.get(key).getProductId())) {
                                    //如果商品满足优惠券,叠加总计
                                    total = total.add(map.get(key).getPrice().multiply(new BigDecimal(numberMap.get(key).getNumber())));
                                }
                            }
                            //计算折扣价格=总计-总计*折扣
                            BigDecimal price = cereBuyerShopCoupon.getReduceMoney().divide(new BigDecimal(10), 2, BigDecimal.ROUND_HALF_UP);
                            BigDecimal discount = total.multiply(price).setScale(2, BigDecimal.ROUND_HALF_UP);
                            cereBuyerShopCoupon.setReduceMoney(total.subtract(discount));
                            discountMap.put(cereBuyerShopCoupon.getId(), cereBuyerShopCoupon);
                            decimal = decimal.add(total.subtract(discount));
                        }
                    }
                } else {
                    //如果是满减券直接叠加
                    discountMap.put(cereBuyerShopCoupon.getId(), cereBuyerShopCoupon);
                    decimal = decimal.add(cereBuyerShopCoupon.getReduceMoney());
                }
            }
        }
        return decimal;
    }

    private void addOrderProduct(List<CartSku> skus, Long orderId, Long shopId,
                                 Map<Long, CartSku> map, List<CartSku> carts, List<OrderProductAttribute> attributes) throws CoBusinessException {
        if (!EmptyUtils.isEmpty(skus)) {
            for (CartSku sku : skus) {
                if (sku.getShopId().equals(shopId)) {
                    if (IntegerEnum.YES.getCode().equals(sku.getSelected())) {
                        //购物车商品,需要删除
                        carts.add(sku);
                    }
                    CereOrderProduct orderProduct = new CereOrderProduct();
                    orderProduct.setOrderId(orderId);
                    orderProduct.setProductId(sku.getProductId());
                    orderProduct.setSkuId(sku.getSkuId());
                    orderProduct.setImage(sku.getImage());
                    orderProduct.setNumber(sku.getNumber());
                    orderProduct.setProductName(sku.getProductName());
                    orderProduct.setProductPrice(sku.getPrice());
                    orderProduct.setSKU(sku.getSKU());
                    orderProduct.setWeight(sku.getWeight());
                    //插入订单商品明细数据
                    cereOrderProductService.insert(orderProduct);
                    //更新库存数量
                    int stockNumber;
                    if (!EmptyUtils.isEmpty(stringRedisService.get(String.valueOf(sku.getSkuId())))) {
                        stockNumber = (int) stringRedisService.get(String.valueOf(sku.getSkuId()));
                    } else {
                        stockNumber = map.get(sku.getSkuId()).getStockNumber();
                    }
                    sku.setStockNumber(stockNumber - sku.getNumber());
                    //更新redis商品库存
                    stringRedisService.set(String.valueOf(sku.getSkuId()), stockNumber - sku.getNumber());
                    //根据规格id查询规格属性数据
                    if (!EmptyUtils.isEmpty(attributes)) {
                        attributes.forEach(a -> {
                            if (sku.getSkuId().equals(a.getSkuId())) {
                                a.setOrderProductId(orderProduct.getOrderProductId());
                            }
                        });
                    }
                }
            }
        }
    }

//    =========================
}
